package com.example.mymvvmdemo.models.add_article;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.view.View;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadActivity;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.ActivityAddArticleBinding;
import com.example.mymvvmdemo.dialog.LoadingAnimDialog;
import com.example.mymvvmdemo.models.add_article.adapter.AddArticleAdapter;
import com.example.mymvvmdemo.models.add_article.adapter.BlogCategoriesAdapter;
import com.example.mymvvmdemo.models.add_article.adapter.BlogTagAdapter;
import com.example.mymvvmdemo.models.add_article.entity.AddArticleEntity;
import com.example.mymvvmdemo.models.add_article.entity.ArticleCreateEntity;
import com.example.mymvvmdemo.models.add_article.entity.BlogCategoriesEntity;
import com.example.mymvvmdemo.models.add_article.entity.BlogTagEntity;
import com.example.mymvvmdemo.net.presenter.GetPresenter;
import com.example.mymvvmdemo.net.presenter.ImagePresenter;
import com.example.mymvvmdemo.net.presenter.PostBodyPresenter;
import com.example.mymvvmdemo.net.presenter.PostPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.FileUtils;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.StrUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddArticleActivity extends BaseLoadActivity<ActivityAddArticleBinding> implements View.OnClickListener, AddArticleAdapter.AddArticleListener, IView.PostBodyView, IView.PostView, IView.ImageView, IView.GetView, BlogTagAdapter.TagListener, BlogCategoriesAdapter.CategoriesListener {

    public static void startAddArticleActivity(Activity activity) {
        Intent intent = new Intent(activity, AddArticleActivity.class);
        activity.startActivity(intent);
    }

    private AddArticleViewModel viewModel;
    private PostBodyPresenter postBodyPresenter;
    private PostPresenter postPresenter;
    private GetPresenter getPresenter;
    private ImagePresenter imagePresenter;
    private AddArticleAdapter adapter;
    private BlogTagAdapter blogTagAdapter;
    private BlogCategoriesAdapter categoriesAdapter;

    /*** 加载时候的Dialog */
    private LoadingAnimDialog loadingDialog;

    @Override
    protected void showDialog() {
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(this, getResources().getString(R.string.load));
        if (!loadingDialog.isShowing()) loadingDialog.show(this);
    }

    @Override
    protected void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.close(this);
        }
    }

    @Override
    protected void initData() {

        viewModel = new ViewModelProvider(this).get(AddArticleViewModel.class);
        postBodyPresenter = new PostBodyPresenter(this);
        postPresenter = new PostPresenter(this);
        getPresenter = new GetPresenter(this);
        imagePresenter = new ImagePresenter(this);
        initTitle(getString(R.string.add_article));
        initAdapter();
        registerGalleryLauncher();
        registerPermissionLauncher();
        startLoadTag();
        startLoadCategories();

    }

    @Override
    protected void initListener() {
        binding.include.ivBack.setOnClickListener(this);
        binding.tvPublish.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_publish:
                startLoadCreate();
                break;
            default:
                break;
        }
    }

    /***********************************自定义方法**************************************/
    public void initTitle(String title) {
        binding.include.tvTitle.setVisibility(View.VISIBLE);
        binding.include.tvTitle.setText(title);
    }

    private void startLoadUpImage() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", "" + viewModel.id);
        imagePresenter.startLoadImage(UrlConstants.uploadImage, hashMap, new File(viewModel.fileUrl), "image", UrlTypeConstants.uploadImage);
    }

    public void startLoadCreate() {
        String title = binding.etTitle.getText().toString();
        String mContent = binding.etContent.getText().toString();
        String summary = binding.etSummary.getText().toString();
        if (StrUtils.isEmpty(title)) {
            toast(R.string.add_article_input_title, ToastUtils.TOA_W);
            return;
        }
        if (StrUtils.isEmpty(mContent)) {
            toast(R.string.add_article_input, ToastUtils.TOA_W);
            return;
        }


        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("title", title);
        hashMap.put("content", mContent);
        hashMap.put("summary", summary);
        hashMap.put("category_id", getCategoryId());
        LogUtils.d("getTagIds():" + getTagIds());
        hashMap.put("tag_ids", getTagIds());
        hashMap.put("status", "draft");
        postBodyPresenter.startLoadPostBody(UrlConstants.articlesCreate, hashMap, UrlTypeConstants.articlesCreate);
    }

    public String getCategoryId() {
        List<BlogCategoriesEntity.DataDTO> dataList = categoriesAdapter.getDataList();
        for (int i = 0; i < dataList.size(); i++) {
            BlogCategoriesEntity.DataDTO dataDTO = dataList.get(i);
            if (dataDTO.isSelect()) {
                return "" + dataDTO.getId();
            }
        }
        return null;
    }

    public String getTagIds() {
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        List<BlogTagEntity.DataDTO> dataList = blogTagAdapter.getDataList();
        for (int i = 0; i < dataList.size(); i++) {
            BlogTagEntity.DataDTO dataDTO = dataList.get(i);
            if (dataDTO.isSelect()) {
                sb.append(dataDTO.getId() + ",");
            }
        }
        String s = sb.toString();
        if (s.contains(",")) {
            String substring = s.substring(0, s.length() - 1);
            return substring + "]";
        } else {
            return sb.toString() + "]";
        }

    }

    public void startArticlesPublish(int id) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", "" + id);
        postPresenter.startLoadPost(UrlConstants.articlesPublish, hashMap, UrlTypeConstants.articlesPublish);
    }

    public void startLoadCategories() {
        HashMap<String, String> hashMap = new HashMap<>();
        getPresenter.startLoadGet(UrlConstants.blogCategories, hashMap, UrlTypeConstants.blogCategories);
    }

    public void startLoadTag() {
        HashMap<String, String> hashMap = new HashMap<>();
        getPresenter.startLoadGet(UrlConstants.blogTag, hashMap, UrlTypeConstants.blogTag);
    }

    private void initAdapter() {

        viewModel.articleList.add(null);
        adapter = new AddArticleAdapter(this, viewModel.articleList);
        adapter.setListener(this);
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 3));


        blogTagAdapter = new BlogTagAdapter(this, viewModel.tagList);
        blogTagAdapter.setListener(this);
        binding.recyclerViewCategories.setAdapter(blogTagAdapter);
        binding.recyclerViewCategories.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        categoriesAdapter = new BlogCategoriesAdapter(this, viewModel.categoriesList);
        categoriesAdapter.setListener(this);
        binding.recyclerViewTag.setAdapter(categoriesAdapter);
        binding.recyclerViewTag.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

    }

    private void registerPermissionLauncher() {
        viewModel.requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
            if (isGranted) {
                openGallery();
            } else {
                toast("需要存储权限才能选择图片", ToastUtils.TOA_W);
            }
        });
    }

    private void registerGalleryLauncher() {
        viewModel.galleryLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                Uri selectedImageUri = result.getData().getData();
                if (selectedImageUri != null && viewModel.currentPosition >= 0) {
                    handleSelectedImage(selectedImageUri);
                }
            }
        });
    }

    private void handleSelectedImage(Uri imageUri) {


        // Convert Uri to File
        File imageFile = FileUtils.getFileByUri(this, imageUri);


        if (imageFile == null) {
            return;
        }

        if (fileIsBig(imageFile)) {
            toast(R.string.file_big, ToastUtils.TOA_W);
            return;
        }

        viewModel.fileUrl = imageFile.getPath();

        // Remove the null placeholder if it's the first image
        if (viewModel.articleList.size() == 1 && viewModel.articleList.get(0) == null) {
            viewModel.articleList.remove(0);
        }

        // Create a new entity with the selected image
        AddArticleEntity entity = new AddArticleEntity(0, true);
        // Store the image URI in the entity (you might need to extend the entity class)
        entity.setImageUri(imageUri);

        if (viewModel.currentPosition >= viewModel.articleList.size()) {
            viewModel.articleList.add(entity);
        } else {
            viewModel.articleList.set(viewModel.currentPosition, entity);
        }

        // Add a new null placeholder for adding more images
        if (viewModel.articleList.get(viewModel.articleList.size() - 1) != null) {
            viewModel.articleList.add(null);
        }

        adapter.notifyDataSetChanged();
    }

    private void checkPermissionAndOpenGallery() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // For Android 13+, check READ_MEDIA_IMAGES
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                viewModel.requestPermissionLauncher.launch(Manifest.permission.READ_MEDIA_IMAGES);
            } else {
                openGallery();
            }
        } else {
            // For Android 6-12, check READ_EXTERNAL_STORAGE
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                viewModel.requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
            } else {
                openGallery();
            }
        }
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        viewModel.galleryLauncher.launch(intent);
    }

    public boolean fileIsBig(File file) {
        long fileSizeInBytes = file.length();
        long fileSizeInMb = fileSizeInBytes / (1024 * 1024 * 2);

        LogUtils.d("文件大小: " + fileSizeInMb + " MB");
        // 判断文件大小是否超过1MB
        if (fileSizeInBytes > 1024 * 1024) { // 1MB in bytes
            return true;
        } else {
            return false;
        }
    }

    /*****************************************适配器点击回调*************************************/
    @Override
    public void onAddArticleClick(int position) {
        viewModel.currentPosition = position;
        checkPermissionAndOpenGallery();
    }

    /***********************************数据请求回调********************************************/
    @Override
    public void loadPostBodySuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.articlesCreate)) {
            loadArticlesCreateSuccess(result, code);
        }
    }

    @Override
    public void loadPostBodyFail(String message, String type) {
        if (type.equals(UrlTypeConstants.articlesCreate)) {
            loadArticlesCreateFail();
        }
    }

    @Override
    public void loadPostBodyAccountError(int code) {

    }

    @Override
    public void loadPostBodyNetWorkError(String type) {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    @Override
    public void loadPostSuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.articlesPublish)) {
            loadArticlesPublishSuccess(result, code);
        }
    }

    @Override
    public void loadPostFail(String message, String type) {
        if (type.equals(UrlTypeConstants.articlesPublish)) {
            loadArticlesPublishFail();
        }
    }

    @Override
    public void loadPostAccountError(int code) {

    }

    @Override
    public void loadPostNetWorkError() {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    @Override
    public void loadImageSuccess(String result, String type, int code) {
        dismissDialog();
        toast(R.string.add_article_publish_success, ToastUtils.TOA_S);
        finish();
    }

    @Override
    public void loadImageFail(String message, String type) {
        dismissDialog();
        toast(R.string.add_article_up_image_fail, ToastUtils.TOA_S);
    }

    @Override
    public void loadImageAccountError(int code) {

    }

    @Override
    public void loadImageNetWorkError(String message) {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    @Override
    public void loadGetSuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.blogCategories)) {
            loadBlogCategoriesSuccess(result, code);
        }
        if (type.equals(UrlTypeConstants.blogTag)) {
            loadBlogTagSuccess(result, code);
        }
    }

    @Override
    public void loadGetFail(String message, String type) {
        if (type.equals(UrlTypeConstants.blogCategories)) {
            loadBlogCategoriesFail();
        }
        if (type.equals(UrlTypeConstants.blogTag)) {
            loadBlogTagFail();
        }
    }

    @Override
    public void loadGetAccountError(int code) {

    }

    @Override
    public void loadGetNetWorkError() {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    /***********************************处理请求后数据********************************************/
    private void loadBlogTagSuccess(String result, int code) {
        if (code != 200) {
            loadBlogTagFail();
            return;
        }
        BlogTagEntity blogTagEntity = gson.fromJson(result, BlogTagEntity.class);
        List<BlogTagEntity.DataDTO> data = blogTagEntity.getData();
        viewModel.tagList.clear();
        viewModel.tagList.addAll(data);
        blogTagAdapter.notifyDataSetChanged();
    }

    private void loadBlogTagFail() {

    }

    private void loadBlogCategoriesSuccess(String result, int code) {
        if (code != 200) {
            loadBlogCategoriesFail();
            return;
        }
        BlogCategoriesEntity blogCategories = gson.fromJson(result, BlogCategoriesEntity.class);
        List<BlogCategoriesEntity.DataDTO> data = blogCategories.getData();
        viewModel.categoriesList.clear();
        viewModel.categoriesList.addAll(data);
        categoriesAdapter.notifyDataSetChanged();

    }

    private void loadBlogCategoriesFail() {

    }


    private void loadArticlesCreateSuccess(String result, int code) {
        if (code != 200) {
            loadArticlesCreateFail();
            return;
        }
        ArticleCreateEntity articleCreateEntity = gson.fromJson(result, ArticleCreateEntity.class);
        ArticleCreateEntity.DataDTO data = articleCreateEntity.getData();
        int id = data.getId();
        viewModel.id = id;
        startArticlesPublish(id);
    }

    private void loadArticlesCreateFail() {
        dismissDialog();
        toast(R.string.add_article_create_fail, ToastUtils.TOA_W);
    }

    private void loadArticlesPublishSuccess(String result, int code) {
        if (code != 200) {
            loadArticlesPublishFail();
            return;
        }

        if (viewModel.fileUrl == null) {
            dismissDialog();
            toast(R.string.add_article_publish_success, ToastUtils.TOA_S);
            finish();
        } else {
            startLoadUpImage();
        }

    }


    private void loadArticlesPublishFail() {
        dismissDialog();
        toast(R.string.add_article_publish_fail, ToastUtils.TOA_W);
    }

    /******************************************列表点击事件*****************************************/
    @Override
    public void onClickTag(int position) {
        BlogTagEntity.DataDTO dataDTO = blogTagAdapter.getDataList().get(position);
        dataDTO.setSelect(!dataDTO.isSelect());
        blogTagAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClickCategories(int position) {
        List<BlogCategoriesEntity.DataDTO> dataList = categoriesAdapter.getDataList();
        for (int i = 0; i < dataList.size(); i++) {
            BlogCategoriesEntity.DataDTO dataDTO = dataList.get(i);
            dataDTO.setSelect(i == position);
        }
        categoriesAdapter.notifyDataSetChanged();
    }

}
